package com.itheima.util;

import com.itheima.dao.SetmealDao;
import com.itheima.pojo.Setmeal;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class StaticHtml{

    @Autowired
    private  FreeMarkerConfigurer freeMarkerConfigurer;

    @Value("${out_put_path}")
    private  String outPutPath;

    @Autowired
    private  SetmealDao setmealDao;

    private static StaticHtml staticHtml;

    public static void generateMobileStaticHtml(){

        //生成静态页面之前查询所有数据
        List<Setmeal> setmeals = staticHtml.setmealDao.getSetmeal();

        //生成套餐列表页面
        staticHtml.generateMobileSetmealListHtml(setmeals);

        //生成套餐详情页面
        staticHtml.generateMobileSetmealDetailHtml(setmeals);


    }

    //生成套餐列表页面
    public static void generateMobileSetmealListHtml(List<Setmeal> setmeals){
        Map map = new HashMap();
        map.put("setmealList",setmeals);
        staticHtml.generateHtml("mobile_setmeal.ftl","m_setmeal.html",map);
    }
    //生成套餐详情页面
    public static void generateMobileSetmealDetailHtml(List<Setmeal> setmeals){
        for (Setmeal setmeal : setmeals) {
            Map map = new HashMap();
            map.put("setmeal",staticHtml.setmealDao.findById(setmeal.getId()));
            staticHtml.generateHtml("mobile_setmeal_detail.ftl","setmeal_detail_"+setmeal.getId()+".html",map);
        }

    }

    //抽取方法，用于生成静态页面
    public static void generateHtml(String templateName,String htmlPageName,Map map){
        //获取配置对象
        Configuration configuration = staticHtml.freeMarkerConfigurer.getConfiguration();
        //加载模板文件
        Writer writer = null;
        try {
            Template template = configuration.getTemplate(templateName);
            //创建输出流，输出静态文件
            // writer=new FileWriter(new File(outPutPath+"/"+htmlPageName));
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(staticHtml.outPutPath + "/" + htmlPageName),"utf-8");
            //输出文件
            template.process(map,outputStreamWriter);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
